package store

import (
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model/req"
	"gorm.io/gorm"
)

type AuthorityStore struct {
	db *gorm.DB
}

func (receiver AuthorityStore) Execute(runnable Runnable) {
	runnable(receiver.db)
}

func (receiver AuthorityStore) Create(req *model.SysAuthority) error {
	return receiver.db.Create(req).Error
}

func (receiver AuthorityStore) Delete(req *model.SysAuthority, isSoftDelete bool) error {
	var err error
	if isSoftDelete {
		err = receiver.db.Delete(req).Error
	} else {
		err = receiver.db.Unscoped().Delete(req).Error
	}
	return err
}

func (receiver AuthorityStore) Update(req *model.SysAuthority) error {
	return receiver.db.Save(req).Error
}

func (receiver AuthorityStore) List(opts req.PageInfo) (*AuthorityList, error) {
	list := &AuthorityList{}
	err := receiver.db.
		Offset((opts.Page-1)*opts.PageSize).
		Limit(opts.PageSize).
		Where("parent_id = ?", "0").
		Find(&list.List).
		Offset(-1).
		Limit(-1).
		Count(&list.Total).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (receiver AuthorityStore) AllList() (*AuthorityList, error) {
	list := &AuthorityList{}
	err := receiver.db.
		Where("parent_id = ?", "0").
		Offset(-1).
		Limit(-1).
		Find(&list.List).
		Count(&list.Total).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

type AuthorityList struct {
	Total int64                `json:"total"`
	List  []model.SysAuthority `json:"list"`
}

func (receiver AuthorityStore) GetAuthorityListByParentId(parentId uint) ([]model.SysAuthority, error) {
	var list []model.SysAuthority
	err := receiver.db.
		Where("parent_id = ?", parentId).
		Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}
